package com.wxb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wxb.common.core.utils.StringUtils;
import com.wxb.common.core.web.domain.AjaxResult;
import com.wxb.common.security.utils.SecurityUtils;
import com.wxb.common.util.Base64Util;
import com.wxb.common.util.CharUtil;
import com.wxb.domain.MallCommentEntity;
import com.wxb.domain.MallCommentPictureEntity;
import com.wxb.domain.MallCouponEntity;
import com.wxb.domain.MallUserCouponEntity;
import com.wxb.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date 2025-05-30 16:07
 * @Version 1.0
 * @Description
 * @ClassName MallCommentController
 **/
@RestController
@RequestMapping("/comment")
public class MallCommentController {
    @Autowired
    private IMallCommentService commentService;
    @Autowired
    private IMallUserService userService;
    @Autowired
    private IMallCommentPictureService commentPictureService;
    @Autowired
    private IMallCouponService apiCouponService;
    @Autowired
    private IMallUserCouponService apiUserCouponService;

    /**
     * 得到request对象
     */
    @Autowired
    protected HttpServletRequest request;

    public com.alibaba.fastjson.JSONObject getJsonRequest() {
        com.alibaba.fastjson.JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = com.alibaba.fastjson.JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
    /**
     * 发表评论
     */
    @PostMapping("post")
    public Object post() {
        Map<String, Object> resultObj = new HashMap<>();
        //
        JSONObject jsonParam = getJsonRequest();
        Integer typeId = jsonParam.getInteger("typeId");
        Integer valueId = jsonParam.getInteger("valueId");
        String content = jsonParam.getString("content");
        JSONArray imagesList = jsonParam.getJSONArray("imagesList");
        MallCommentEntity commentEntity = new MallCommentEntity();
        commentEntity.setTypeId(typeId);
        commentEntity.setValueId(valueId);
        commentEntity.setContent(content);
        commentEntity.setStatus(0);
        //
        commentEntity.setAddTime(System.currentTimeMillis() / 1000);
        commentEntity.setUserId(SecurityUtils.getUserId());
        commentEntity.setContent(Base64Util.encode(commentEntity.getContent()));
        Integer insertId = commentService.save(commentEntity);
        //
        if (insertId > 0 && null != imagesList && imagesList.size() > 0) {
            int i = 0;
            for (Object imgLink : imagesList) {
                i++;
                MallCommentPictureEntity pictureVo = new MallCommentPictureEntity();
                pictureVo.setCommentId(insertId);
                pictureVo.setPicUrl(imgLink.toString());
                pictureVo.setSortOrder(i);
                commentPictureService.save(pictureVo);
            }
        }
        // 是否领取优惠券
        if (insertId > 0 && typeId == 0) {
            // 当前评价的次数
            Map<String, Object> param = new HashMap<>();
            param.put("valueId", valueId);
            List<MallCommentEntity> commentVos = commentService.queryList(param);
            boolean hasComment = false;
            for (MallCommentEntity commentVo : commentVos) {
                if (commentVo.getUserId().equals(SecurityUtils.getUserId())
                        && !commentVo.getId().equals(insertId)) {
                    hasComment = true;
                }
            }
            if (!hasComment) {
                Map<String, Object> couponParam = new HashMap<>();
                couponParam.put("sendType", 6);
                MallCouponEntity newCouponConfig = apiCouponService.queryMaxUserEnableCoupon(couponParam);
                if (null != newCouponConfig
                        && newCouponConfig.getMinTransmitNum() >= commentVos.size()) {
                    MallUserCouponEntity userCouponVo = new MallUserCouponEntity();
                    userCouponVo.setAddTime(new Date());
                    userCouponVo.setCouponId(newCouponConfig.getId());
                    userCouponVo.setCouponNumber(CharUtil.getRandomString(12));
                    userCouponVo.setUserId(SecurityUtils.getUserId());
                    apiUserCouponService.save(userCouponVo);
                    resultObj.put("coupon", newCouponConfig);
                }
            }
        }
        if (insertId > 0) {
            return AjaxResult.success("评论添加成功", resultObj);
        } else {
            return AjaxResult.error("评论保存失败");
        }
    }

    /**
     */
    @PostMapping("count")
    public Object count(Integer typeId, Integer valueId) {
        Map<String, Object> resultObj = new HashMap<>();
        //
        Map<String, Object> param = new HashMap<>();
        param.put("typeId", typeId);
        param.put("valueId", valueId);
        Integer allCount = commentService.queryTotal(param);
        Integer hasPicCount = commentService.queryhasPicTotal(param);
        //
        resultObj.put("allCount", allCount);
        resultObj.put("hasPicCount", hasPicCount);
        return AjaxResult.success(resultObj);
    }

    /**
     * @param typeId
     * @param valueId
     * @param showType 选择评论的类型 0 全部， 1 只显示图片
     * @param page
     * @param size
     * @return
     */
    @PostMapping("list")
    public Object list(Integer typeId, Integer valueId, Integer showType,
                       @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size,
                       String sort, String order) {
        Map<String, Object> param = new HashMap<>();
        param.put("typeId", typeId);
        param.put("valueId", valueId);
        param.put("page", page);
        param.put("limit", size);
        if (StringUtils.isEmpty(sort)) {
            param.put("order", "desc");
        } else {
            param.put("order", sort);
        }
        if (StringUtils.isEmpty(order)) {
            param.put("sidx", "id");
        } else {
            param.put("sidx", order);
        }
        if (null != showType && showType == 1) {
            param.put("hasPic", 1);
        }
        //查询列表数据
        List<MallCommentEntity> commentList = commentService.queryList(param);
        //
        for (MallCommentEntity commentItem : commentList) {
            commentItem.setContent(Base64Util.decode(commentItem.getContent()));
            commentItem.setUserInfo(userService.queryObject(commentItem.getUserId()));

            Map<String, Object> paramPicture = new HashMap<>();
            paramPicture.put("commentId", commentItem.getId());
            List<MallCommentPictureEntity> commentPictureEntities = commentPictureService.queryList(paramPicture);
            commentItem.setPicList(commentPictureEntities);
        }
        return AjaxResult.success(commentList);
    }
}
